/*
 Copyright 2021 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

//  register service worker
// import swURL from 'sw:../service-worker.js';
const swURL = 'http://localhost:5173/service-worker.js';

// Register the service worker
if ('serviceWorker' in navigator) {
  // Wait for the 'load' event to not block other work
  window.addEventListener('load', async () => {
    // Try to register the service worker.
    try {
      const reg = await navigator.serviceWorker.register(swURL);
      console.log('Service worker registered! 😎', reg);
    } catch (err) {
      console.log('😥 Service worker registration failed: ', err);
    }
  });
}


// 添加主屏幕图标
let deferredPrompt;

// 监听beforeinstallprompt事件
window.addEventListener('beforeinstallprompt', (e) => {
  // 阻止Chrome 67及更早版本自动显示安装提示
  e.preventDefault();
  // 保存事件，以便稍后再触发
  deferredPrompt = e;
  // 更新UI通知用户可以将网站添加到主屏幕
  // 例如：显示一个“添加到主屏幕”的按钮
  // showAddToHomeScreenButton();
});

function showAddToHomeScreenButton() {
  // 显示一个按钮，让用户可以点击来添加网站到主屏幕
  // 假设有一个id为“addToHomeScreen”的按钮
  const button = document.getElementById('addToHomeScreen');
  button.style.display = 'block';

  // 当用户点击按钮后触发提示
  button.addEventListener('click', () => {
    // 隐藏按钮，因为我们已经处理了事件
    button.style.display = 'none';
    // 显示安装提示
    deferredPrompt.prompt();
    // 等待用户响应安装提示
    deferredPrompt.userChoice.then((choiceResult) => {
      if (choiceResult.outcome === 'accepted') {
        console.log('用户接受将网站添加到主屏幕');
      } else {
        console.log('用户拒绝将网站添加到主屏幕');
      }
      deferredPrompt = null;
    });
  });
}

window.addEventListener('DOMContentLoaded', async () => {
  // Set up the editor
  const { Editor } = await import('./app/editor.js');
  const editor = new Editor(document.body);

  // Set up the menu
  const { Menu } = await import('./app/menu.js');
  new Menu(document.querySelector('.actions'), editor);

  // Set the initial state in the editor
  const defaultText = `# Welcome to PWA Edit!\n\nTo leave the editing area, press the \`esc\` key, then \`tab\` or \`shift+tab\`.`;

  editor.setContent(defaultText);
});
